<template>
  <div>
    <Layout>
      <Sider hide-trigger :style="{background: '#fff', width: '260px', maxWidth: '260px', flex: '0 0 260px'}">
        <Card title="应用" icon="md-apps" :padding="5" shadow style="width: 250px; margin:0px 5px;">
          <CellGroup @on-click="onClientSelected">
            <Cell v-for='(client,index) in clientList' :title='client.clientName' :selected='client.selected' :name="index" />
          </CellGroup>
        </Card>
      </Sider>
      <Content :style="{padding: '0px', minHeight: '280px', background: '#fff'}">
        <Card :title="contextTitle" icon="md-apps" :padding="5" shadow style="margin:0px 5px;">
          <div style="float: right;"  slot="extra">
          <ButtonGroup>
            <Button @click="addRootAction">新增</Button>
          </ButtonGroup>
          </div>
          <Tree :data="treeNodes" :render="renderTreeNode" @on-toggle-expand="treeNodeExpanded"></Tree>
        </Card>
        <!-- <Spin size="large" fix v-if="loading"></Spin> -->
      </Content>
    </Layout>

    <Modal
        :title="modalTitle"
        v-model="modalShow"
        :mask-closable="false"
        :closable="false"
        :footer-hide="true"
        scrollable
        class-name="vertical-center-modal">
      <Form :ref="formRef" :model="formData" label-position="right" :rules="formValidateRule" :label-width="100">
        <input v-model="formData.resourceId" name="resourceId" type="hidden">
        <input v-model="formData.clientId" name="clientId" type="hidden">
        <input v-model="formData.parentId" name="parentId" type="hidden">
        <FormItem label="资源编号" prop="resourceId" v-if="actionType === 'edit'">
            {{ formData.resourceId }}
        </FormItem>
        <FormItem label="资源名称" prop="resourceName">
            <Input v-model="formData.resourceName" name="resourceName" placeholder="资源名称"></Input>
        </FormItem>
        <FormItem label="资源路径" prop="url">
            <Input v-model="formData.url" name="url" placeholder="资源路径"></Input>
        </FormItem>
        <FormItem label="权限标识" prop="permission">
            <Input v-model="formData.permission" name="permission" placeholder="权限标识"></Input>
        </FormItem>
        <FormItem label="资源类型">
            <RadioGroup v-model="formData.resourceType">
              <Radio label="0">菜单</Radio>
              <Radio label="1">操作</Radio>
            </RadioGroup>
        </FormItem>
        <FormItem label="排序" prop="orderValue">
            <Input v-model="formData.orderValue" name="orderValue" placeholder="排序"></Input>
        </FormItem>

        <FormItem>
           <div style="float: right;">
             <Button style="margin-right: 10px" @click="formCancelHandle">取消</Button>
            <Button type="primary" @click="formSaveHandle">保存</Button>
           </div>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import Vue from 'vue'
import { mapActions } from 'vuex'
export default {
  name: 'resourceManage',
  components: {},
  data () {
    return {
      tableColumns: [
        {
          type: 'index',
          title: '序号',
          align: 'center',
          width: 60
        },
        {
          title: '资源名称',
          key: 'resourceName'
        }
      ],
      columnKey: 'resourceId',
      listData: [],
      loading: false,
      totalCount: 100,
      pageIndex: 1,
      modalTitle: 'title',
      modalShow: false,
      formRef: 'editForm',
      formData: {},
      formValidateRule: {},
      clientList: [],
      selectedClientIndex: 0,
      selectedClient: {},
      resources: [],
      treeNodes: [],
      expandNodes: [],
      // 操作类型
      actionType: ''
    }
  },
  methods: {
    ...mapActions('resourceStore', [
      'getValidateRule',
      'listAll',
      'listChild',
      'save',
      'delete'
    ]),
    ...mapActions({
      loadClientAll: 'clientStore/loadAll'
    }),
    loadClients () {
      if (this.clientList.length < 1) {
        this.loadClientAll()
          .then(res => {
            this.clientList = res.data.map(client => {
              let cli = client
              cli.selected = false
              return cli
            })
            this.selectedClientIndex = 0
            this.clientList[this.selectedClientIndex].selected = true
            this.selectedClient = this.clientList[this.selectedClientIndex]

            this.loadData()
          })
          .catch(err => {
            console.log(err)
          })
      }
    },
    loadData: function () {
      // console.log('>> load-data')
      this.loading = true
      this.listAll({ clientId: this.selectedClient.clientId })
        .then(res => {
          // console.log(res.data)
          if (res.data && res.data instanceof Array) {
            let listData = res.data.map((item) => {
              return this.$contextUtils.convertObjectNumberPropertieToString(item)
            })
            this.resources = listData
          } else {
            this.resources = []
          }

          // console.log(this.resources)

          let nodes = []
          this.nodesBuild(nodes, [null, ''])
          // console.log(nodes)
          this.treeNodes = nodes

          this.loading = false
        })
        .catch(err => {
          console.log(err)
          this.loading = false
        })
    },
    nodesBuild: function (nodes, parentId) {
      // console.log(this.resources)
      for (let idx in this.resources) {
        const resource = this.resources[idx]
        // console.log(resource)
        if (parentId.indexOf(resource.parentId) > -1) {
          let node = {
            nodeKey: resource.resourceId,
            title: resource.resourceName,
            clientId: resource.clientId,
            resourceId: resource.resourceId,
            resourceName: resource.resourceName,
            parentId: resource.parentId,
            url: resource.url,
            permission: resource.permission,
            resourceType: resource.resourceType,
            orderValue: resource.orderValue,
            expand: false,
            children: []
          }

          if (this.expandNodes.indexOf(resource.resourceId) > -1) {
            node.expand = true
          }
          this.nodesBuild(node.children, [resource.resourceId])
          // console.log(node)
          nodes.push(node)
        }
      }
    },
    clearFormData: function () {
      this.$refs[this.formRef].resetFields()
      this.formData = {}
    },
    addRootAction () {
      this.addChildAction({ root: null, node: null, data: null })
    },
    addChildAction ({ root, node, data }) {
      this.clearFormData()
      this.actionType = 'add'
      this.formData = {
        resourceType: '0',
        orderValue: 100,
        clientId: this.selectedClient.clientId,
        parentId: data ? data.resourceId : ''
      }
      // console.log(root, node, data)
      this.modalTitle = '新增'
      this.modalShow = true
    },
    editAction ({ root, node, data }) {
      this.clearFormData()
      this.actionType = 'edit'
      this.modalTitle = '编辑'
      this.modalShow = true

      let editData = []
      for (let prop in data) {
        editData[prop] = data[prop]
      }
      this.formData = this.$contextUtils.convertObjectNumberPropertieToString(editData)
    },
    deleteAction ({ root, node, data }) {
      this.$Modal.confirm({
        title: '删除',
        content: '确定要删除么？删除时会删除选中项和其所有子项',
        onOk: () => {
          this.confirmDeleteAction(data)
        }
      })
    },
    confirmDeleteAction (data) {
      console.log(data.resourceId)
      this.delete({
        resourceId: data.resourceId,
        clientId: data.clientId
      })
        .then(res => {
          // console.log(res)
          this.$Message.info('删除成功')
          this.loadData()
        })
        .catch(err => {
          this.$Message.error(err)
        })
    },
    formCancelHandle () {
      this.modalShow = false
    },
    formSaveHandle () {
      console.log(' >>> save ')
      this.$refs[this.formRef].validate(valid => {
        if (!valid) {
          this.$Message.error('输入信息不合法')
        } else {
          // requestData.authorizedGrantTypes = grantTypes

          this.save(this.formData)
            .then(res => {
              this.clearFormData()
              this.modalShow = false
              this.$Message.info('保存成功')
              this.loadData()
            })
            .catch(err => {
              this.$Message.info(err)
            })
        }
      })
    },
    onClientSelected (index) {
      // console.log(' select click', index)
      let oldSelectedItem = this.clientList[this.selectedClientIndex]
      oldSelectedItem.selected = false
      Vue.set(this.clientList, this.selectedClientIndex, oldSelectedItem)

      let selectedItem = this.clientList[index]
      selectedItem.selected = true
      Vue.set(this.clientList, index, selectedItem)
      this.selectedClientIndex = parseInt(index)
      this.selectedClient = this.clientList[this.selectedClientIndex]

      this.expandNodes = []

      this.loadData()
      // console.log(this.getSelectedClientId())
    },
    getSelectedClientId () {
      return this.selectedClient
    },
    renderTreeNode (h, { root, node, data }) {
      // console.log('>>>', data)
      return h('span', {
        class: ['node-span'],
        style: {
          display: 'inline-block',
          width: '100%'
          // borderBottom: 'dotted 1px #666'
        }
      }, [
        h('span', [
          h('Icon', {
            props: {
              type: 'ios-folder-outline'
            },
            style: {
              marginRight: '8px'
            }
          }),
          h('span', data.resourceId + '-' + data.title)
        ]),
        h('span', {
          style: {
            display: 'inline-block',
            float: 'right',
            marginRight: '32px'
          }
        }, [
          h('Button', {
            props: Object.assign({}, this.buttonProps, {
              icon: 'ios-add',
              size: 'small'
            }),
            style: {
              marginRight: '8px'
            },
            on: {
              click: () => { this.addChildAction({ root, node, data }) }
            }
          }, '添加子资源'),
          h('Button', {
            props: Object.assign({}, this.buttonProps, {
              icon: 'ios-build',
              size: 'small'
            }),
            style: {
              marginRight: '8px'
            },
            on: {
              click: () => { this.editAction({ root, node, data }) }
            }
          }, '编辑'),
          h('Button', {
            props: Object.assign({}, this.buttonProps, {
              icon: 'ios-remove',
              size: 'small'
            }),
            on: {
              click: () => { this.deleteAction({ root, node, data }) }
            }
          }, '删除')
        ])

      ])
    },
    // 资源树展开状态改变处理
    treeNodeExpanded (data) {
      if (data.expand) {
        this.expandNodes.push(data.resourceId)
      } else {
        let idx = this.expandNodes.indexOf(data.resourceId)
        this.expandNodes.splice(idx, 1)
      }
      // console.log(this.expandNodes)
    }
  },
  computed: {
    contextTitle: function () {
      return this.selectedClient.clientName + '的资源'
    }
  },
  created () {
    // 加载验证规则
    this.getValidateRule().then(val => {
      this.formValidateRule = {}
      for (let ruleColumn in val) {
        this.formValidateRule[ruleColumn] = val[ruleColumn]
      }
    })

    this.loadClients()
  }
}
</script>

<style lang="less">
.node-span {
  padding-top: 5px;
  padding-bottom: 5px;
}
.node-span:hover {
  border-bottom: 1px dotted #ddd
}
</style>
